/**
 * 
 */
package any.tag.gwt.client.ui;

import any.gwt.client.util.DispacherContainer;
import any.gwt.client.util.DispatchEvent;
import any.gwt.client.util.DispatcherListener;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * TODO: Doc me
 * 
 * @author keke <keke@codehaus.org>
 * @version
 * @revision $Revision:$
 */
public class TagEditDialog extends DialogBox implements ClickListener,
        DispatcherListener {
    private final Button  cancel;
    private final Button  save;
    private final TextBox tagBox;
    private final String  tags;
    private final String  uri;

    public TagEditDialog(final String uri, final String tags) {
        super(true, true);
        this.uri = uri;
        this.tags = tags;
        final FlowPanel outer = new FlowPanel();
        tagBox = new TextBox();
        tagBox.addKeyboardListener(new KeyboardListenerAdapter() {

            public void onKeyPress(final Widget sender, final char keyCode,
                    final int modifiers) {
                if (keyCode == KEY_ENTER) {
                    doTag();
                }
            }
        });
        save = new Button("Save");
        cancel = new Button("Cancel");
        save.addClickListener(this);
        cancel.addClickListener(this);
        outer.add(tagBox);
        final HorizontalPanel p = new HorizontalPanel();
        p.add(save);
        p.add(cancel);
        outer.add(p);
        setWidget(outer);
    }

    public void fireDispatchEvent(final DispatchEvent event) {
        if (event.isConsumed()) {
            return;
        }
        if (event.getName().equals("tagsSaved")) {
            hide();
        }

    }

    public void onClick(final Widget sender) {
        if (sender == cancel) {
            hide();
        } else {
            doTag();
        }
    }

    private void doTag() {
        DispacherContainer.getGlobalDispatcher().dispatch(
                new DispatchEvent(this, new Object[] { tagBox.getText().trim(),
                        uri }, "saveTags"));
    }

    protected void onLoad() {
        tagBox.setText(tags);
        tagBox.setFocus(true);
    }

}
